package com.may.wind.controller;

import com.may.wind.encrypt.annotation.Decrypt;
import com.may.wind.encrypt.annotation.Encrypt;
import com.may.wind.entity.Book;
import com.may.wind.pojo.Result;
import com.may.wind.pojo.Upload;
import com.may.wind.service.BookService;
import com.may.wind.util.SnowflakeIdWorker;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Decoder;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

/**
 * @author 风
 */
@RestController
@Api(tags = "图书馆相关API")
public class LibraryController {
    @Autowired
    BookService bookService;

    /**
     * 获取所有书籍
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "查询所有书籍", httpMethod = "GET")
    @GetMapping("/api/library/getBooks")
    public Result<List<Book>> getList() throws Exception {
        List<Book> list = bookService.getList();
        return Result.ok().data("books", list);
    }

    /**
     * 添加或更新书籍
     *
     * @param book
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "添加或更新书籍", notes = "添加或更新书籍时使用", httpMethod = "POST")
    @ApiImplicitParam(name = "book", value = "书籍信息", required = true)
    @PostMapping("/api/library/addBook")
    @Decrypt
    @Encrypt
    public Result<Book> addOrUpdate(Book book) throws Exception {
        bookService.addOrUpdate(book);
        return Result.ok().data("book", book);
    }

    /**
     * 删除书籍
     *
     * @param book
     * @throws Exception
     */
    @ApiOperation(value = "删除书籍", notes = "删除书籍时使用", httpMethod = "DELETE")
    @ApiImplicitParam(name = "book", value = "书籍信息", required = true)
    @ApiResponse(code = 200, message = "删除成功")
    @DeleteMapping("/api/library/deleteBook")
    @Decrypt
    @Encrypt
    public Result delete(Book book) throws Exception {
        bookService.deleteById(book.getId());
        return Result.ok();
    }

    /**
     * 依据书籍分类获取书籍
     *
     * @param categoryId
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "查询书籍", notes = "依据书籍分类查询书籍", httpMethod = "GET")
    @ApiImplicitParam(name = "categoryId", value = "书籍分类ID", required = true, paramType = "path", dataType = "int")
    @GetMapping("/api/library/categories/{categoryId}/books")
    public Result<List<Book>> getListByCategory(@PathVariable("categoryId") int categoryId) throws Exception {
        List<Book> list;
        if (0 != categoryId) {
            list = bookService.getListByCategory(categoryId);
        } else {
            list = bookService.getList();
        }
        return Result.ok().data("books", list);
    }

    /**
     * 搜索
     *
     * @param keywords
     * @return
     */
    @ApiOperation(value = "搜索书籍", notes = "依据关键字搜索书籍", httpMethod = "GET")
    @ApiImplicitParam(name = "keywords", value = "关键字", dataType = "query")
    @GetMapping("/api/library/search")
    public Result<List<Book>> searchResult(@RequestParam("keywords") String keywords) {
        List<Book> list;
        // 关键词为空时查询出所有书籍
        if ("".equals(keywords)) {
            list = bookService.getList();
        } else {
            list = bookService.searchBooks(keywords);
        }
        return Result.ok().data("books", list);
    }

    /**
     * 封面上传
     *
     * @param upload
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "上传书籍封面", httpMethod = "POST")
    @ApiImplicitParam(name = "upload", value = "封面文件信息", required = true, paramType = "query")
    @PostMapping("/api/library/covers")
    @Encrypt
    @Decrypt
    public Result<String> coversUpload(Upload upload) throws Exception {
        String folder = "E://Project//Java//may//img//";
        SnowflakeIdWorker worker = new SnowflakeIdWorker(0, 0);
        String workerId = Long.toBinaryString(worker.nextId());
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            // 解密
            byte[] bytes = null;
            if (upload.imgResult.indexOf("data:image/jpeg;base64,") != -1) {
                bytes = decoder.decodeBuffer(upload.imgResult.replaceAll("data:image/jpeg;base64,", ""));
            } else {
                if (upload.imgResult.indexOf("data:image/png;base64,") != -1) {
                    bytes = decoder.decodeBuffer(upload.imgResult.replaceAll("data:image/png;base64,", ""));
                } else {
                    bytes = decoder.decodeBuffer(upload.imgResult.replaceAll("data:image/jpg;base64,", ""));
                }
            }

            // 处理数据
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {
                    bytes[i] += 256;
                }
            }
            OutputStream out = new FileOutputStream(folder + workerId + upload.fileName);
            out.write(bytes);
            out.flush();
            out.close();
            String imgUrl = "http://127.0.0.1:8443/api/file/img/" + workerId + upload.fileName;
            return Result.ok().data("imgUrl", imgUrl);
        } catch (IOException ioException) {
            ioException.printStackTrace();
            return Result.error().data("imgUrl", "");
        }
    }
}
